import { Application } from "@pixi/app";
import { BaseTexture, Filter, Texture, Ticker } from "@pixi/core";
import { Sprite } from "@pixi/sprite";
import { fragmentShader, vertexShader } from "./shader";

// 3200 × 1280
const hotBallon = "https://d1.music.126.net/dmusic/obj/w5nDkMKQwrLDjDzCm8Om/35474208378/cc6d/202432415632/compressed_5a5b9b4ea998bc0a24ececa961df60cf.mp4";
// 1500 x 844
const treaBox = "https://d1.music.126.net/dmusic/obj/w5nDkMKQwrLDjDzCm8Om/44314135848/6027/20246421332/compressed_c4ddfb30d32bb3c36cdaf917f9205220.mp4";

class XySprite extends Sprite {
    set x(value: number) {
        if (this.transform.position.x !== value) {
            this.emit("positionChange", { x: value });
        }
        super.x = value;
    }

    get x() {
        return super.x;
    }

    set y(value: number) {
        if (this.transform.position.y != value) {
            this.emit("positionChange", { y: value });
        }
        super.y = value;
    }

    get y() {
        return super.y;
    }
}

const clamp = (x: number, min: number, max: number) => {
    return x < min ? min : x > max ? max : x;
}

const isHidden = () => {
    return document.hidden || document.visibilityState === "hidden"
}

async function createVideo(url: string): Promise<HTMLVideoElement> {
    return new Promise((resolve, reject) => {
        let video = document.createElement("video");
        video.src = url;
        video.loop = false;
        video.autoplay = false;
        video.muted = true;
        video.volume = 0.0;
        video.controls = true;
        video.crossOrigin = "anonymous"
        video.playsInline = true; // ios必须设置 才能在静音的情况下自动播放
        video.setAttribute('webkit-playsinline', 'true')
        video.id = "video-player-" + Date.now()
        video.preload = "metadata";
        // video.style.display = "none";

        document.getElementsByTagName('body')?.[0]?.appendChild?.(video);
        video.addEventListener('loadedmetadata', () => {
            resolve(video)
        })
        video.addEventListener('pause', () => {
            console.log('pause')
        })
        video.addEventListener('loadstart', () => {
            console.log('loadstart')
        })
        video.addEventListener('loadeddata', () => {
            console.log('loadeddata')
        })
        video.addEventListener('progress', () => {
            console.log('progress')
        })
        video.addEventListener('canplay', () => {
            console.log('canplay')
        })
        video.addEventListener('playing', () => {
            console.log('playing')
        })
        video.addEventListener('ended', () => {
            console.log('ended')
        })
        video.addEventListener('seeking', () => {
            console.log('seeking')
        })
        video.addEventListener('seeked', () => {
            console.log('seeked')
        })
        video.addEventListener('error', reject)
    })
}

export async function addAlphaVideo(app: Application) {
    let vodom = await createVideo(treaBox);
    let baseTexture = BaseTexture.from(vodom, {
        resourceOptions: {
            autoPlay: false,
        }
    })
    let videoTexture = Texture.from(baseTexture);

    baseTexture.on('destroyed', () => {
        console.log('video destroyed')
    })

    console.log('width', baseTexture.width, baseTexture.height)

    let s = new Sprite(videoTexture)
    s.x = 0
    s.y = 0
    s.width = baseTexture.width / 2
    s.height = baseTexture.height;

    {
        let f = new Filter(vertexShader, fragmentShader)
        f.resolution = 2
        s.filters = [f]
    }

    let duration = vodom.duration * 1000;

    const playSegments = (segments: number[], loop: boolean | number = false) => {
        return new Promise((resolve, reject) => {
            let startTime = clamp(segments[0], 0, duration)
            let endTime = segments[1] ? clamp(segments[1], 0, duration) : duration

            vodom.currentTime = startTime / 1000;

            let count = 1;
            let maxCount = typeof loop === "number" ? loop : Infinity;

            let fn = () => {
                let ct = vodom.currentTime;

                if (ct * 1e3 >= endTime) {
                    count++;
                    if (!loop || count > maxCount) {
                        Ticker.shared.remove(fn)
                        resolve(true);
                    } else {
                        if (!isHidden()) {
                            vodom.currentTime = startTime / 1000;
                            vodom.play();
                        }
                    }
                } else {
                    // 如果因为其他原因暂停了（ios切到后台为了省电 会自动停止），重新播放
                    if (vodom.paused) {
                        vodom.play();
                    }
                }
            }

            Ticker.shared.add(fn);
            vodom.play().catch(reject)
        })
    }

    let maxx = app.screen.width

    console.log('maxx', maxx)

    let step = 1;

    Ticker.shared.add(() => {
        // let x = s.x + step;
        // if (x >= maxx) {
        //     step *= -1;
        // }
        // if (x <= -100) {
        //     step *= -1;
        // }

        // s.x = x;
        // s.rotation += 0.01;
    })

    console.log('paused', vodom.paused)

    playSegments([0,], true);

    app.stage.addChild(s)
}